<template>
  <div class="register-container">
    <h2>注册</h2>
    <form @submit.prevent="handleRegister">
      <!-- 用户名、密码、确认密码部分 -->
      <div class="form-group">
        <label>用户名：</label>
        <input v-model="username" required />
      </div>
      <div class="form-group">
        <label>密码：</label>
        <input type="password" v-model="password" required />
      </div>
      <div class="form-group">
        <label>确认密码：</label>
        <input type="password" v-model="confirm" required />
      </div>

      <!-- 手机号 + 验证码按钮 -->
      <div class="form-row">
        <div class="form-group">
          <label>手机号：</label>
          <input v-model="phoneNumber" placeholder="请输入11位手机号" />
        </div>
        <button
          type="button"
          :disabled="sending || countdown > 0"
          @click="onSendCode"
          class="code-btn"
        >
          {{ countdown > 0 ? countdown + "秒后重新发送" : "发送验证码" }}
        </button>
      </div>

      <!-- 验证码输入 -->
      <div class="form-group">
        <label>验证码：</label>
        <input v-model="verificationCode" placeholder="请输入6位验证码" />
      </div>

      <!-- 角色选择（单选） -->
      <div class="form-group">
        <label>选择角色：</label>
        <div class="role-options">
          <label class="role-option">
            <input 
              type="radio" 
              v-model="role" 
              value="USER" 
              name="role" 
              @change="onRoleChange"
            /> 用户
          </label>
          <label class="role-option">
            <input 
              type="radio" 
              v-model="role" 
              value="MERCHANT" 
              name="role"
              @change="onRoleChange"
            /> 商家
          </label>
        </div>
      </div>

      <button type="submit">注册</button>
      <p v-if="error" class="error">{{ error }}</p>
      <p v-if="success" class="success">{{ success }}</p>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { register, sendVerificationCode } from '@/utils/auth'

const username = ref('')
const password = ref('')
const confirm = ref('')
const phoneNumber = ref('')
const verificationCode = ref('')
const role = ref('USER') // 默认选中用户
const error = ref('')
const success = ref('')

// 验证码相关
const sending = ref(false)
const countdown = ref(0)
let timer = null

// 角色选择处理
const onRoleChange = (e) => {
  role.value = e.target.value
}

// 发送验证码
const onSendCode = async () => {
  error.value = ''
  success.value = ''
  
  if (!/^\d{11}$/.test(phoneNumber.value)) {
    error.value = '请输入有效的11位手机号'
    return
  }
  
  sending.value = true
  try {
    const res = await sendVerificationCode(phoneNumber.value, 'register')
    if (res.data.code === 0) {
      success.value = '验证码已发送，请注意查收'
      startCountdown()
    } else {
      error.value = res.data.message || '验证码发送失败'
    }
  } catch (err) {
    error.value = '验证码发送失败，请稍后重试'
    console.error('验证码发送错误:', err)
  } finally {
    sending.value = false
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 注册处理
const handleRegister = async () => {
  error.value = ''
  
  // 表单验证
  if (password.value !== confirm.value) {
    error.value = '两次密码输入不一致'
    return
  }
  
  if (!verificationCode.value || !/^\d{6}$/.test(verificationCode.value)) {
    error.value = '请输入6位验证码'
    return
  }

  try {
    const res = await register(
      username.value,
      password.value,
      phoneNumber.value,
      verificationCode.value,
      role.value
    )
    
    if (res.data.code === 0) {
      success.value = '注册成功，请登录'
      // 清空表单
      username.value = ''
      password.value = ''
      confirm.value = ''
      phoneNumber.value = ''
      verificationCode.value = ''
    } else {
      error.value = res.data.message || '注册失败'
    }
  } catch (err) {
    error.value = '注册失败，请稍后重试'
    console.error('注册错误:', err)
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.register-container {
  max-width: 360px;
  margin: 60px auto;
  font-family: "Inter", sans-serif;
  padding: 20px;
}

h2 {
  text-align: center;
  font-size: 26px;
  font-weight: 700;
  color: #111827;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 6px;
}

input {
  width: 100%;
  padding: 12px 14px;
  font-size: 14px;
  border: 1px solid #d1d5db;
  border-radius: 10px;
  outline: none;
  box-sizing: border-box;
}

.form-row {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.code-btn {
  flex-shrink: 0;
  height: 45px;
  padding: 12px 10px;
  white-space: nowrap;
  background-color: #111827;
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.code-btn:hover {
  background-color: #1f2937;
}

.code-btn:disabled {
  background-color: #9ca3af;
  cursor: not-allowed;
}

.role-options {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.role-option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

button[type="submit"] {
  width: 100%;
  background-color: #111827;
  color: white;
  padding: 12px;
  font-size: 16px;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  margin-top: 10px;
  transition: background-color 0.3s;
}

button[type="submit"]:hover {
  background-color: #1f2937;
}

.error {
  color: #ef4444;
  margin-top: 10px;
  text-align: center;
}

.success {
  color: #10b981;
  margin-top: 10px;
  text-align: center;
}
</style>